/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.alien.admin.modules.deploy.service.impl;

import com.alien.admin.modules.deploy.domain.DpImageBuildTpl;
import com.alien.admin.modules.deploy.domain.DpJenkinsInstance;
import com.alien.admin.modules.deploy.domain.DpServer;
import com.alien.admin.modules.deploy.repository.DpJenkinsInstanceRepository;
import com.alien.admin.modules.deploy.repository.DpServerRepository;
import com.alien.admin.modules.system.domain.User;
import com.alien.admin.modules.system.repository.UserRepository;
import com.alien.admin.utils.*;
import lombok.RequiredArgsConstructor;
import com.alien.admin.modules.deploy.repository.DpImageBuildTplRepository;
import com.alien.admin.modules.deploy.service.DpImageBuildTplService;
import com.alien.admin.modules.deploy.service.dto.DpImageBuildTplDto;
import com.alien.admin.modules.deploy.service.dto.DpImageBuildTplQueryCriteria;
import com.alien.admin.modules.deploy.service.mapstruct.DpImageBuildTplMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.persistence.OneToOne;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zengzhifang
 * @website https://el-admin.vip
 * @description 服务实现
 * @date 2021-09-17
 **/
@Service
@RequiredArgsConstructor
public class DpImageBuildTplServiceImpl implements DpImageBuildTplService {

    private final DpImageBuildTplRepository dpImageBuildTplRepository;
    private final DpImageBuildTplMapper dpImageBuildTplMapper;
    private final UserRepository userRepository;
    private final DpJenkinsInstanceRepository dpJenkinsInstanceRepository;
    private final DpServerRepository dpServerRepository;

    @Override
    public Map<String, Object> queryAll(DpImageBuildTplQueryCriteria criteria, Pageable pageable) {
        Page<DpImageBuildTpl> page = dpImageBuildTplRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        List<DpImageBuildTpl> dpImageBuildTplList = page.getContent();
        for (DpImageBuildTpl dpImageBuildTpl : dpImageBuildTplList) {
            Optional<DpJenkinsInstance> optional = dpJenkinsInstanceRepository.findById(dpImageBuildTpl.getJenkinsId());
            if (optional.isPresent()) {
                dpImageBuildTpl.setJenkinsName(optional.get().getName());
            }
        }
        return PageUtil.toPage(page.map(dpImageBuildTplMapper::toDto));
    }

    @Override
    public List<DpImageBuildTplDto> queryAll(DpImageBuildTplQueryCriteria criteria) {
        return dpImageBuildTplMapper.toDto(dpImageBuildTplRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public DpImageBuildTplDto getByProjectIdAndEnv(DpImageBuildTplQueryCriteria criteria) {
        if (criteria.getProjectId() != null) {
            Optional<DpServer> optional = dpServerRepository.findById(Long.valueOf(criteria.getProjectId()));
            criteria.setFrameworkType(optional.get().getCodeType());
        }
        List<DpImageBuildTplDto> list = dpImageBuildTplMapper.toDto(dpImageBuildTplRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    @Override
    @Transactional
    public DpImageBuildTplDto findById(Integer id) {
        DpImageBuildTpl dpImageBuildTpl = dpImageBuildTplRepository.findById(id).orElseGet(DpImageBuildTpl::new);
        ValidationUtil.isNull(dpImageBuildTpl.getId(), "DpImageBuildTpl", "id", id);
        return dpImageBuildTplMapper.toDto(dpImageBuildTpl);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DpImageBuildTplDto create(DpImageBuildTpl resources) {

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername());
        resources.setCreateBy(user.getUsername());
        resources.setUpdateBy(user.getUsername());
        resources.setCreateTime(timestamp);
        resources.setUpdateTime(timestamp);

        return dpImageBuildTplMapper.toDto(dpImageBuildTplRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DpImageBuildTpl resources) {
        DpImageBuildTpl dpImageBuildTpl = dpImageBuildTplRepository.findById(resources.getId()).orElseGet(DpImageBuildTpl::new);
        ValidationUtil.isNull(dpImageBuildTpl.getId(), "DpImageBuildTpl", "id", resources.getId());

        User user = userRepository.findByUsername(SecurityUtils.getCurrentUsername());
        resources.setUpdateBy(user.getUsername());
        dpImageBuildTpl.setUpdateTime(new Timestamp(System.currentTimeMillis()));

        dpImageBuildTpl.copy(resources);
        dpImageBuildTplRepository.save(dpImageBuildTpl);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            dpImageBuildTplRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<DpImageBuildTplDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (DpImageBuildTplDto dpImageBuildTpl : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("环境", dpImageBuildTpl.getEnv());
            map.put("镜像名称", dpImageBuildTpl.getName());
            map.put("框架类型", dpImageBuildTpl.getFrameworkType());
            map.put("Jenkins实例id", dpImageBuildTpl.getJenkinsId());
            map.put("参数表单", dpImageBuildTpl.getParamForm());
            map.put("job脚本内容", dpImageBuildTpl.getContent());
            map.put("创建人", dpImageBuildTpl.getCreateBy());
            map.put("修改人", dpImageBuildTpl.getUpdateBy());
            map.put("创建日期", dpImageBuildTpl.getCreateTime());
            map.put("更新时间", dpImageBuildTpl.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}